package Demo4;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Comparable 和 Comparator 接口的实例
 * Comparable 比较死板 对类的入侵性太强，对 compareTo 重写后，该类默认就使用这个比较法，没办法轻易改动
 * Comparator 比较器 更为灵活
 * 根据业务来选择使用哪个
 */

class Studen implements Comparable<Studen>{
    public String name;
    public int age;

    public Studen(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Studen{" +
                "name='" + this.name + '\'' +
                ", age=" + this.age +
                '}';
    }

    @Override
    public int compareTo(Studen o) {
        return o.age - this.age;
    }
}

//比较器
class AgeCompertor implements Comparator<Studen>{
    @Override
    public int compare(Studen o1, Studen o2) {
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Studen>{
    @Override
    public int compare(Studen o1, Studen o2) {
        return o1.name.compareTo(o2.name);
    }
}



public class Text {
    public static void main(String[] args) {
        Studen[] studen = new Studen[] {
                new Studen("lisan", 95),
                new Studen("lisi", 96),
                new Studen("wangwu", 97),
                new Studen("zhangsan", 92),
        };

        NameComparator nameComparator = new NameComparator();
        Arrays.sort(studen);
        System.out.println(Arrays.toString(studen));
    }
    public static void sort(Studen[] studens) {
        for (int i = 0; i < studens.length - 1; i++) {
            for (int j = 0; j < studens.length - 1 -i; j++) {
                if(studens[j].compareTo(studens[ j+1])  > 0) {
                    Studen tmp = studens[j];
                    studens[j] = studens[j + 1];
                    studens[j + 1] = tmp;
                }
            }
        }
    }


    public static void main1(String[] args) {
        int a = 10;
        int b = 1;
        Studen studen = new Studen("zhangsan" ,18);
        Studen studen1 = new Studen("lilei",6);
        //System.out.println(a < b);

        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(studen, studen1));

//        AgeCompertor ageCompertor = new AgeCompertor();
//        System.out.println(ageCompertor.compare(studen, studen1));

       // System.out.println(studen.compareTo(studen1));
    }
}
